#include "CBullet.h"
#include "SGD Wrappers\CSGD_TextureManager.h"
#include "Messaging\CSGD_EventSystem.h"
#include "Messaging\CSGD_MessageSystem.h"
#include "SGD Wrappers\CSGD_FModManager.h"
#include "Game.h"
#include "CTurret.h"

CBullet::CBullet()
{
	m_pOwner = NULL;
	m_nType = OBJ_BULLET;
	m_fRotation = 0.0f;
	m_nLazerHit = -1;


	CSGD_EventSystem::GetInstance()->RegisterClient("turretdestroyed", this);
}

CBullet::~CBullet()
{
	if(m_pOwner)
		m_pOwner->Release();

	CSGD_EventSystem::GetInstance()->UnregisterClient("turretdestroyed", this);
}

void CBullet::SetOwner(CBase* _pOwner)
{
	if(m_pOwner)
		m_pOwner->Release();

	m_pOwner=_pOwner;

	if(NULL != m_pOwner)
		m_pOwner->AddRef();
}

void CBullet::Update(float _fElapsedTime)
{
	CBase::Update(_fElapsedTime);
	if(m_fPosX+m_nWidth > CGame::GetInstance()->GetWindowWidth() || m_fPosX < 0
		|| m_fPosY+m_nHeight > CGame::GetInstance()->GetWindowHeight() || m_fPosY < 0)
	{
		CSGD_MessageSystem::GetInstance()->SendMsg(new CDestroyBulletMessage(this));
	}
}

void CBullet::Render()
{
	RECT bulletRect = {0,0,32,32};
	CSGD_TextureManager::GetInstance()->Draw(GetTexID(),(int)m_fPosX,(int)m_fPosY, 1.0f, 1.0f, &bulletRect, m_nWidth*0.5f, m_nHeight*0.5f, m_fRotation);
}

bool CBullet::CheckCollision(IBaseInterface *_pIBase)
{
	bool hit = CBase::CheckCollison(_pIBase);

	if(hit)
	{
		if(_pIBase != m_pOwner)
		{
			CSGD_FModManager::GetInstance()->PlaySoundA(m_nLazerHit);
			CSGD_MessageSystem::GetInstance()->SendMsg(new CDestroyBulletMessage(this));

			if(_pIBase->GetType() == OBJ_TANK)
			{
				CTurret* ownerTurret = (CTurret*) m_pOwner;
				ownerTurret->SetRank(ownerTurret->GetRank()+1);
			}
		}
	}

	return hit;
}

RECT CBullet::GetCollisonRect()
{
	RECT collisonRect = {(long)m_fPosX,(long)m_fPosY,(long)m_fPosX + m_nWidth,(long)m_fPosY+ m_nHeight};

	return collisonRect;
}

void CBullet::HandleEvent(CEvent* pEvent)
{
	if (pEvent->GetEventID() == "turretdestroyed")
	{
		if( pEvent->GetParam() == m_pOwner )
		{
			m_pOwner->Release();
			m_pOwner = NULL;
		}
	}
}